(function ($) {
	var pullArr = [],pullingArr = [false,false,false],pageArr = [0,0,0],pullData = [[],[],[]];
	var typeArr = ['C','Q','N'] //C评论 Q提问 N笔记
	var Limit = 20
	var tomcat=''
	var subID=localStorage['trainSubID']||''
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		console.log('aaa')
	}
	function getVideoInfoList(index){
		var pullDom = pullArr[index]
		if (pullingArr[index]) {
			pullDom.endPullUpToRefresh()
			return;
		}
		pullingArr[index] = true
		var parr = subID+'^'+typeArr[index]; //C评论 Q提问 N笔记
		var pdict = {'parr':parr,'start':pageArr[index],'limit':Limit}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:LoadDrillVideoInfo','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			pullingArr[index] = false
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				pullDom.endPullUpToRefresh();
				return
			}
			var dataArr = result.data
			if (pageArr[index] == 0) {
				pullData[index] = dataArr
				$('#UL'+typeArr[index])[0].innerHTML = ''
			}else{
				pullData[index] = pullData[index].concat(dataArr)
			}
			updateUI(dataArr,'UL'+typeArr[index])
			if (dataArr.length < Limit) {
				pullDom.endPullUpToRefresh(true);
			}else{
				pullDom.endPullUpToRefresh();
			}
			pageArr[index] += dataArr.length;
		}, function(errorStr) {
			pullDom.endPullUpToRefresh();
			pullingArr[index] = false
		});
	}
	function updateUI(dataArr,ulId){
		var ulDom = $('#'+ulId)[0]
		for(var i=0; i<dataArr.length; i++){
			var dict = dataArr[i]
			var PerPic = dict['PerPic']
			if (PerPic != '') {
				PerPic = '<img src="'+tomcat + PerPic+'"/>'
			}else{
				var name = dict['userName']
				name = name.substring(name.length-2,name.length)
				PerPic = '<div class="imgText">'+name+'</div>'
			}
			var html = '<div class="headImg">'+PerPic+'</div>'+
				'<div class="nurInfo">'+dict['userName']+' &nbsp;&nbsp;  '+dict['infoTime']+'</div>'+
				'<div class="nurContent">'+dict['context']+'</div>';
			if (ulId == 'ULQ' && dict['Answer'] != '') {
				html += '<div class="nurContent">【回答】'+dict['Answer']+'</div>';
			}
			var newLi = document.createElement('li')
			newLi.setAttribute('class','mui-table-view-cell')
			newLi.innerHTML = html
			ulDom.appendChild(newLi)
		}
		//'<div class="supportArea"><div class="supportText">3</div><div class="nurfont nur-tubiao_dianzan"></div></div>';
		//newLi.querySelector('.supportArea').addEventListener('tap',supportBtnTapped)
	}
	// 收藏按钮点击
	function storeBtnTapped(){
		if (this.getAttribute('class').indexOf('mui-active') != -1) {
			this.classList.remove('mui-active')
		}else{
			this.classList.add('mui-active')
		}
	}
	// 下载按钮点击
	function downloadBtnTapped(){
		setTimeout(function(){
			mui.toast('下载完成')
		},500)
	}
	//评论和笔记的发布按钮点击
	function sureBtnTapped(){
		var popoverId = this.getAttribute('data-id');
		var content = $('#myText')[0].value;
		if (content == '') {
			mui.toast('请录入内容后再发布')
			return
		}
		var type = $('#editPopo')[0].getAttribute('data-id');
		var parr = subID+'^'+type
		var pdict = {'parr':parr,'info':content}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:SaveDrillVideoInfo','params':JSON.stringify(pdict),'type':'Method'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				return
			}
			showOrHidepopover('hide')
			if (type == 'C') {
				resetRefresh(0)
			}else if (type == 'Q') {
				resetRefresh(1)
			}else{
				resetRefresh(2)
			}
		}, function(errorStr) {
			mui.toast(errorStr)
		});
	}
	
	function supportBtnTapped(){
		var text = this.querySelector('.supportText');
		if (this.getAttribute('class').indexOf('mui-active') != -1) {
			this.classList.remove('mui-active')
			text.innerText=parseInt(text.innerText) - 1
		}else{
			this.classList.add('mui-active')
			text.innerText=parseInt(text.innerText) + 1
		}
	}
	
	function baseSetup(){
		if (subID == '' || subID == 'undefined') {
			return
		}
		var perInfo = app.getState()
		tomcat = perInfo.TomcatUrl+'/'
		console.log(window.location.search)
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		var slider = document.getElementById('slider');
		slider.addEventListener('slide', function(event) {
			var index = event.detail.slideNumber;
			refreshMainPage(index)
			$('#sliderIndicator .mui-indicator[data-index="'+index+'"]')[0].classList.add('mui-active');
		});
		mui('#slider').on('tap','#updownBtn',function(){
			var dom = $('.mui-content')[0]
			var classStr = dom.getAttribute('class')
			var flag = ''
			if (classStr.indexOf('dhc-active') != -1) {
				dom.classList.remove('dhc-active')
				flag = '0'
			}else{
				dom.classList.add('dhc-active')
				flag = '1'
			}
			top.postMessage({"origin":'trainCNQ',flag:flag}, '*');
		})
		var indicators = document.querySelectorAll('#sliderIndicator .mui-indicator');
		for (var i = 0; i < indicators.length;i++) {
			indicators[i].addEventListener('tap',function(){
				var oldActive = $('#sliderIndicator .mui-indicator.mui-active')[0];
				if (oldActive) {
					if (oldActive == this) {
						return
					}
					oldActive.classList.remove('mui-active')
				}
				var newIndex = parseInt(this.getAttribute('data-index'))
				refreshMainPage(newIndex)
				this.classList.add('mui-active')
				mui('#slider').slider().gotoItem(newIndex,100)
			});
		}
		//评论 提问 笔记
		pullArr[0] = $($('#scrollC')[0]).pullToRefresh({
			up: {
				callback: function() {
					getVideoInfoList(0)
				}
			}
		});
		pullArr[1] = $($('#scrollQ')[0]).pullToRefresh({
			up: {
				callback: function() {
					getVideoInfoList(1)
				}
			}
		});
		pullArr[2] = $($('#scrollN')[0]).pullToRefresh({
			up: {
				callback: function() {
					getVideoInfoList(2)
				}
			}
		});
		getVideoInfoList(0)
		getVideoInfoList(1)
		getVideoInfoList(2)
		
		$('#slider').on('tap','.editBtn',function(){//写评论/提问/笔记按钮
			$('#popoTitle')[0].innerText = '请撰写您的'+this.innerText.replace('写','')
			$('#myText')[0].value = ''
			showOrHidepopover('show',this.id.replace('btn',''))
		});
		
		$('.mui-popover').on('tap','.closeBtn',function(){//popover的关闭按钮
			showOrHidepopover('hide')
		});
		$('.mui-popover').on('tap','.sureBtn',sureBtnTapped);//popover的发布按钮
	}
	
	function refreshMainPage(newIndex){
		if (newIndex == undefined) {
			resetRefresh(0);
			resetRefresh(1)
			resetRefresh(2)
			return
		}
		resetRefresh(newIndex)
	}
	function resetRefresh(index){
		pageArr[index] = 0;
		pullData[index] = []
		if (pullArr[index]) {
			pullArr[index].refresh(true)
		}
		getVideoInfoList(index);
		$('#wrapper'+typeArr[index]).scroll().scrollTo(0,0,100);
	}

	function showOrHidepopover(type,popoType){
		var popover = $('#editPopo')[0];
		var popoBackdrop = $('#popoBackdrop')[0];
		if (type == "show") {
			popover.setAttribute('data-id',popoType)
			if (popover) {
				popover.classList.add('mui-active')
			}
			popoBackdrop.classList.add('dhc-active')
		}else{
			if (popover) {
				popover.classList.remove('mui-active')
			}
			popoBackdrop.classList.remove('dhc-active')
			$('#myText')[0].blur();
		}
	}
})(mui)